package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.context.BaseContext;
import com.heima.mapper.RoleMapper;
import com.heima.mapper.UserMapper;
import com.heima.pojo.Role;
import com.heima.pojo.User;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.dto.UserAddDTO;
import com.heima.pojo.dto.UserPageDTO;
import com.heima.pojo.entity.VmType;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.pojo.vo.UserPageVO;
import com.heima.result.PageResult;
import com.heima.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper RoleMapper;
    @Override
    public LoginUserVo login(LoginDto dto) {

        if(dto == null){
            //参数异常
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getLoginName,dto.getLoginName());
        User user = userMapper.selectOne(wrapper);

        if(user == null){ //代表用户不存在得

        }
        if(!user.getPassword().equals(dto.getPassword())){ //代表密码错误

        }
        //密码相等
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        loginUserVo.setToken(UUID.randomUUID().toString());
        return loginUserVo;
    }
    /**
     *人员查询
     */
    @Override
    public PageResult<UserPageVO> page(UserPageDTO dto) {
        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());
        Page<UserPageVO> page =userMapper.page(dto);
        page.forEach( u->{
         Role role = RoleMapper.roleById(u.getRoleId());
            u.setRole(role);
        });
        return new PageResult<>(dto.getPageIndex(),dto.getPageSize(),page.getPages(),page.getTotal(),page.getResult());
    }
    /**
     * 修改人员
     */
    @Override
    public boolean update(Integer userId, UserAddDTO dto) {
        User user = new User();
        user.setId(userId);
        BeanUtils.copyProperties(dto, user);
        int result = userMapper.updatea(user);
        return result>0;
    }
    /**
     * 根据id删除
     */
    @Override
    public boolean del(Integer userId) {
       int result = userMapper.del(userId);
        return result>0;
    }
}
